#include <avr/io.h>
#include "spi.h"

void spi_init(void)
{
	// SCK, SS, MOSI as outputs
	SPI_DDR |= (1<<SPI_SCK)|(1<<SPI_SS)|(1<<SPI_MOSI);

	// MISO as input
	SPI_DDR &= ~(1<<SPI_MISO);

	// INIT interface, Master, set clock rate fck/128
	SPCR = (1<<SPE)|(1<<MSTR)/*|(1<<SPR1)*/|(1<<SPR0);
}

uint8_t spi_readwrite(uint8_t data)
{
	// set data to send into SPI data register
	SPDR = data;
	// Wait for transmission complete 
	while(!(SPSR & (1<<SPIF)));
	// return data read from SPI
	return SPDR;
}

uint8_t spi_read(void)
{
	return spi_readwrite(SPI_DONT_CARE);
}

void spi_write(uint8_t data)
{
	spi_readwrite(data);
}

void spi_select_can()
{
	// Sets SPI_SCK for CAN
	//SPCR &= ~(1<<CPOL);
	//SPCR &= ~(1<<CPHA);

	SPI_SS_LOW();
}

void spi_select_lcd()
{
	// Sets SPI_SCK for LCD
	SPCR |= (1<<CPOL) | (1<<CPHA);
	
	// Selects LCD
	SPI_SS_HIGH();
}
